from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """添加购物车数据序列化返回"""
    sku_id = serializers.IntegerField(min_value=1, label='商品id')
    count = serializers.IntegerField(label='数量', min_value=1)
    selected = serializers.BooleanField(default=True, label='勾选状态')

    def validate(self, attrs):
        # 校验商品是否存在
        sku_id = attrs['sku_id']
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        # 校验库存是否充足
        if sku.stock < attrs['count']:
            raise serializers.ValidationError('商品库存不足')
        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    """序列化返回购物车页面的商品数据"""
    selected = serializers.BooleanField(label='勾选状态')
    count = serializers.IntegerField(label='数量')

    class Meta:
        model = SKU
        fields = ['id', 'name', 'selected', 'count', 'default_image_url', 'price']


class CartDeleteSerializer(serializers.Serializer):
    """
    删除购物车数据序列化器
    """
    sku_id = serializers.IntegerField(label='商品id', min_value=1)

    def validate_sku_id(self, value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value
